/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Client;

import GUI.Utility;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author d_frEak
 */
public class TorrentConverter {

    public String link;
    public String name;
    public String hashname;
    public long filelength;
    public long piecelength;
    public long npieces = 0;
    public ArrayList<String> pieces = new ArrayList<String>();

    public String hashing(String teks) {
        //inisiaiisasi algoritma sha1
        MessageDigest md = null;

        try {
            md = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(TorrentConverter.class.getName()).log(Level.SEVERE, null, ex);
        }

        byte[] output;
        //hash nama file
        md.update(teks.getBytes());
        output = md.digest();
        return bytesToHex(output);
    }

    public String getTracker(File input) {
        String temp = "";
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream(input);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            // Read File Line By Line
            strLine = br.readLine();
            temp = strLine;

            // Close the input stream
            in.close();
        } catch (Exception e) {// Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
        return temp;
    }

    public String getName(File input) {
        String temp = "";
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream(input);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            // Read File Line By Line
            strLine = br.readLine();
            strLine = br.readLine();
            temp = strLine;

            // Close the input stream
            in.close();
        } catch (Exception e) {// Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
        return temp;
    }

    public String getFileSize(File input) {
        String temp = "";
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream(input);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            // Read File Line By Line
            strLine = br.readLine();
            strLine = br.readLine();
            strLine = br.readLine();
            temp = strLine;

            // Close the input stream
            in.close();
        } catch (Exception e) {// Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
        return temp;
    }

    public String getPieceSize(File input) {
        String temp = "";
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream(input);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            // Read File Line By Line
            strLine = br.readLine();
            strLine = br.readLine();
            strLine = br.readLine();
            strLine = br.readLine();
            temp = strLine;

            // Close the input stream
            in.close();
        } catch (Exception e) {// Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
        return temp;
    }

    public String getPieceCount(File input) {
        String temp = "";
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream(input);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            // Read File Line By Line
            strLine = br.readLine();
            strLine = br.readLine();
            strLine = br.readLine();
            strLine = br.readLine();
            strLine = br.readLine();
            temp = strLine;

            // Close the input stream
            in.close();
        } catch (Exception e) {// Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
        return temp;
    }

    public static String bytesToHex(byte[] b) {
        char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        StringBuffer buf = new StringBuffer();
        for (int j = 0; j < b.length; j++) {
            buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
            buf.append(hexDigit[b[j] & 0x0f]);
        }
        return buf.toString();
    }

    public void load(File input) {
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream(input);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            int i = 0, j = 0;
            // Read File Line By Line
            strLine = br.readLine();
            link = strLine;
            strLine = br.readLine();
            name = strLine;
            strLine = br.readLine();
            filelength = Long.parseLong(strLine);
            strLine = br.readLine();
            piecelength = Long.parseLong(strLine);
            strLine = br.readLine();
            npieces = Long.parseLong(strLine);
            while ((strLine = br.readLine()) != null) {
                // Print the content on the console
                // System.out.println(strLine);
                pieces.add(strLine);
            }
            // Close the input stream
            in.close();
        } catch (Exception e) {// Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

        //inisiaiisasi algoritma sha1
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(TorrentConverter.class.getName()).log(Level.SEVERE, null, ex);
        }
        byte[] output;
        //hash nama file
        md.update(name.getBytes());
        output = md.digest();
        hashname = bytesToHex(output);
    }

    public void save(File f) {
        try {
            // Create file
            FileWriter fstream = new FileWriter(f.getAbsolutePath());
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(link);
            out.newLine();
            out.write(name);
            out.newLine();
            out.write(String.valueOf(filelength));
            out.newLine();
            out.write(String.valueOf(piecelength));
            out.newLine();
            out.write(String.valueOf(npieces));
            for (int i = 0; i < pieces.size(); i++) {
                out.newLine();
                out.write(pieces.get(i));
            }

            //Close the output stream
            out.close();
            if(!Utility.isFileExist(name))
                Utility.saveTorrent(name, String.valueOf(filelength), String.valueOf(piecelength), String.valueOf(npieces));
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
        
    }

    public void convert(File input, String tLink, int tPiecelength) {
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream(input);
            link = tLink;
            name = input.getName();
            filelength = input.length();

            if (tPiecelength == 0) //automatic
            {
                automatics();
//                            System.out.println("piece length : "+piecelength);
                tPiecelength = Integer.parseInt(String.valueOf(piecelength));
            } else {
                piecelength = tPiecelength;
            }

            byte[] currBytes = new byte[(int) input.length()];
            byte[] tempBytes = new byte[tPiecelength];
            fstream.read(currBytes);
//                        System.out.println(currBytes[1]);
            //inisiaiisasi algoritma sha1
            MessageDigest md = MessageDigest.getInstance("SHA1");
            int indexCB = 0;
            byte[] output;
            while ((indexCB + 1) * tPiecelength < currBytes.length) {
                tempBytes = new byte[tPiecelength];
                for (int i = 0; i < tPiecelength; i++) {
                    tempBytes[i] = currBytes[indexCB * tPiecelength + i];
//                                System.out.print(tempBytes[i]);
                }
//                            System.out.println("");
                indexCB++;
                md.update(tempBytes);
                output = md.digest();
//                            System.out.println("\n"+indexCB+" -> "+bytesToHex(output));
                pieces.add(bytesToHex(output));
            }
            //1 kali lagi yang terakhir
            if ((indexCB + 1) * tPiecelength != currBytes.length) {
                tempBytes = new byte[tPiecelength];
                int y = 0;
                for (int i = indexCB * tPiecelength; i < currBytes.length; i++) {
                    tempBytes[y] = currBytes[i];
//                                System.out.print(tempBytes[y]);
                    y++;
                }
                indexCB++;
                md.update(tempBytes);
                output = md.digest();
//                            System.out.println("\n"+indexCB+" -> "+bytesToHex(output));
                pieces.add(bytesToHex(output));
            }
            //hash nama file
            md.update(name.getBytes());
            output = md.digest();
            hashname = bytesToHex(output);

            //catat n
            npieces = pieces.size();
        } catch (Exception e) {// Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }

    public void print() {
        System.out.println("Link : " + link);
        System.out.println("Name : " + name);
        System.out.println("Hash Name : " + hashname);
        System.out.println("File Length : " + filelength);
        System.out.println("Piece Length : " + piecelength);
        System.out.println("N Piece : " + npieces);
        for (int i = 0; i < pieces.size(); i++) {
            System.out.println("Piece " + (i + 1) + " : " + pieces.get(i));
        }
    }

    public void automatics() {
        long size = 0;
        long ukuran[] = {32, 64, 128, 256, 512, 1024, 2048, 4096};
        int i = 0;
        int loop = 1;
//        System.out.println(ukuran.length);
        while (i < ukuran.length && loop == 1) {
            piecelength = ukuran[i];
//            System.out.println(piecelength);
            size = filelength / piecelength;
            if (filelength % piecelength != 0) {
                size++;
            }

            if (size <= 1500) {
                loop = 0;
            }
            i++;
        }
//        System.out.println("brenti");
    }

    public static void main(String[] args) {
        // TODO code application logic here
        TorrentConverter tes = new TorrentConverter();
//        tes.convert(new File("Test.jpg"), "sd", 64);
//        tes.convert(new File("Test.jpg"), "sd", 0);
//        tes.print();
//        tes.save(new File("tes.txt"));
//        tes.load(new File("tes.txt"));
//        tes.print();
        System.out.println(tes.hashing(tes.getName(new File("tes.txt"))));
        System.out.println(tes.getName(new File("tes.txt")));
        System.out.println(tes.getTracker(new File("tes.txt")));
    }
}
